package com.youngjun.gateway.service.impl;

import com.youngjun.gateway.service.RouteDefinitionService;
import com.youngjun.gateway.service.SwaggerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import springfox.documentation.swagger.web.SwaggerResource;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author virgojun
 */
@Primary
@Service
public class SwaggerServiceImpl implements SwaggerService {

	public static final String API_URI = "/v2/api-docs";

	@Autowired
	private RouteDefinitionService routeDefinitionService;

	@Override
	public List<SwaggerResource> get() {
		List<SwaggerResource> resources = new ArrayList<>();
		List<RouteDefinition> routes = new ArrayList<>();
		routeDefinitionService.getRouteDefinitions().subscribe(routes::add);
		routes.forEach(routeDefinition -> routeDefinition.getPredicates().stream()
				//Path和名字一致
				.filter(predicateDefinition -> "Path".equalsIgnoreCase(predicateDefinition.getName()))
//				.filter(predicateDefinition -> !filterIgnorePropertiesConfig.getSwaggerProviders().contains(routeDefinition.getId()))
				.forEach(predicateDefinition -> {
					String pattern = predicateDefinition.getArgs().get("pattern");
					if(pattern != null){
						pattern=pattern.replace("/**", API_URI);
					}
					resources.add(swaggerResource(routeDefinition.getId(),pattern));
				})
		);
		return resources.stream().sorted(Comparator.comparing(SwaggerResource::getName))
				.collect(Collectors.toList());
	}

	private SwaggerResource swaggerResource(String name, String location) {
		SwaggerResource swaggerResource = new SwaggerResource();
		swaggerResource.setName(name);
		swaggerResource.setLocation(location);
		swaggerResource.setSwaggerVersion("2.0");
		return swaggerResource;
	}
}